package com.mindainfo.configCenter.apk.web;

import com.mindainfo.configCenter.base.dao.impl.MorphiaDao;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * Created by MD-01 on 2017/1/13.
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Resource
    private MorphiaDao morphiaDao;


    @RequestMapping("/{id}")
    public void file(@PathVariable("id")String id,
                     HttpServletRequest request,
                     HttpServletResponse response){
        if(StringUtils.isEmpty(id)){
            return;
        }
        GridFSDownloadStream is = morphiaDao.getInputStream(id);
        GridFSFile gridFSFile = is.getGridFSFile();
        String fileName = gridFSFile.getFilename();
        String agent = request.getHeader("User-Agent");

        try{
            if(agent!=null && agent.toLowerCase().indexOf("firefox") > 0){
                fileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            }else{
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            response.setContentLength((int)gridFSFile.getLength());
            IOUtils.copy(is, response.getOutputStream());
            is.close();
            response.flushBuffer();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
